package com.yangcangclub.system.domain;

import com.yangcangclub.commons.config.SysConfig;
import com.yangcangclub.commons.exception.ApolloException;
import com.yangcangclub.commons.result.MessageEnum;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 图片上传
 */
@Component
public class ImgUpload {
    private static Logger logger = LoggerFactory.getLogger(ImgUpload.class);
    @Autowired
    SysConfig sysConfig;

    static Auth auth;

    public Auth getAuth() {
        if(null==auth) {
            auth = Auth.create(sysConfig.getImgAccessKey(), sysConfig.getImgSecretKey());
        }
        return auth;
    }

    public String upload(byte[] data,String fileType) {
        //密钥配置
          Auth auth = getAuth();
        //创建上传对象
          UploadManager uploadManager = new UploadManager();
        String key=System.currentTimeMillis()+fileType;
        try {
             uploadManager.put(data, key, auth.uploadToken(sysConfig.getImgBucket()));

            return sysConfig.getImgHead()+key;
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error(e.response.toString());
            throw new ApolloException(MessageEnum.FAILURE);
        }
    }

    public String getToken() {
        //密钥配置
        Auth auth = getAuth();
        return auth.uploadToken(sysConfig.getImgBucket());
    }

}
